package com.guapi.controller;

import com.guapi.entity.User;
import com.guapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping({"","/","/index"})
    public String index(Model model, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        model.addAttribute("user", user);
        return "/page/index";
    }

    @GetMapping("/login")
    public String loginIndex() {
        return "page/login";
    }

    @PostMapping("/login")
    public String login(
            @RequestParam(name = "username")String username,
            @RequestParam(name = "password")String password,
                        Model model, HttpServletRequest request) {
        User user = userService.getUserByUsername(username);
        String pwd = user.getPassword();
        if (pwd.equals(password)) {
            model.addAttribute("user", user);
            request.getSession().setAttribute("user", user);
            request.getSession().setMaxInactiveInterval(30*60);
            return "redirect:/index";
        } else {
            return "page/failed";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus){
        session.removeAttribute("user");
        sessionStatus.setComplete();
        return "redirect:/index";
    }


}
